package com.itheima.listener;

import javax.servlet.*;
import javax.servlet.http.*;
import javax.servlet.annotation.*;

@WebListener
public class MyListener implements ServletContextListener, HttpSessionListener, HttpSessionAttributeListener {

    public MyListener() {
    }

    @Override
    public void contextInitialized(ServletContextEvent sce) {
        /* This method is called when the servlet context is initialized(when the Web application is deployed). */
        //监听服务器打开
        System.out.println("服务器开启了!");
    }

    @Override
    public void contextDestroyed(ServletContextEvent sce) {
        /* This method is called when the servlet Context is undeployed or Application Server shuts down. */
        //监听服务器关闭
        System.out.println("关闭了服务器!");
    }

    @Override
    public void sessionCreated(HttpSessionEvent se) {
        /* Session is created. */
        //监听会话创建
        HttpSession session = se.getSession();
        System.out.println("创建了会话:" + session);
    }

    @Override
    public void sessionDestroyed(HttpSessionEvent se) {
        /* Session is destroyed. */
        //监听会话关闭
        HttpSession session = se.getSession();
        System.out.println("销毁了会话:" + session);
    }

    @Override
    public void attributeAdded(HttpSessionBindingEvent sbe) {
        /* This method is called when an attribute is added to a session. */
        //监听向上下文域添加值
        String name = sbe.getName();
        Object value = sbe.getValue();
        System.out.println("向上会话加了数据  键:" + name + " 值:" + value);
    }

    @Override
    public void attributeRemoved(HttpSessionBindingEvent sbe) {
        /* This method is called when an attribute is removed from a session. */
        //监听从上下文域销毁值
        String name = sbe.getName();
        Object value = sbe.getValue();
        System.out.println("从会话中删除了:  键:" +name + " 值:" + value);
    }

    @Override
    public void attributeReplaced(HttpSessionBindingEvent sbe) {
        /* This method is called when an attribute is replaced in a session. */
        //监听从上下文域中修改值
        String name = sbe.getName();
        Object value = sbe.getValue();
        System.out.println("从会话中修改了:  键:" +name + " 值:" + value);
        System.out.println("修改之前:  键:" +name + " 值:" + value);
    }
}
